using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using TanashCMS.Business;
using NHibernate;

public partial class manager_pages_build : CMSManagementPageBase
{
    private WebPage mCurrentPage = null;
    public WebPage CurrentPage { get { return mCurrentPage; } set { mCurrentPage = value; } }
    public bool ForBlog { get { return Request.QueryString["for"] != null && Request.QueryString["for"] == "blog"; } }

    protected override void OnPreInit(EventArgs e)
    {
        if (Request.QueryString["id"] != null)
            mCurrentPage = Configuration.GetCurrentSession().Get<WebPage>(int.Parse(Request.QueryString["id"]));

        base.OnPreInit(e);
    }

    protected override void OnInit(EventArgs e)
    {
        Session["FCKeditor:UserFilesPath"] = mWebsite.WebsiteFolder;

        Page.ClientScript.RegisterOnSubmitStatement(
        fckContent.GetType(),
        "editor",
        "FCKeditorAPI.GetInstance('" + fckContent.ClientID + "').UpdateLinkedField();");

//        if (mCurrentPage.PageType == WebPageType.SmartPage)
//            lbConvertToSmartPage.Text = "Convert to Standard Page";

        linkPageList.NavigateUrl = ForBlog ? "~/manager/blog" : "~/manager/pages";

        base.OnInit(e);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack && mCurrentPage != null)
            DataBind();

        if (!User.IsInRole("administrator"))
            lbConvertToSmartPage.Visible = false;


    }
    protected void fvWebPage_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
    {
        if (mCurrentPage != null)
        {
            ShowSystemFeedback("The web page has been saved");
        }

        mWebsite.NeedsPublish = true;
        Configuration.GetCurrentSession().SaveOrUpdate(mWebsite);
        Configuration.GetCurrentSession().Flush();
    }

    public override void DataBind()
    {
        TitleTextBox.Text = mCurrentPage.Title;
        txtPageKey.Text = mCurrentPage.ItemKey;

        ddlPageStatus.SelectedIndex = (int)mCurrentPage.State;

        BindMasterPages();

        if (ddlMasterPage.Items.FindByValue(mCurrentPage.MasterPage) != null)
            ddlMasterPage.SelectedValue = mCurrentPage.MasterPage;
        fckContent.Value = mCurrentPage.HTMLContent;

        litGUID.Text = mCurrentPage.GUID;

        linkPageList.NavigateUrl = ForBlog ? "~/manager/blog" : "~/manager/pages";

        base.DataBind();
    }

    private void BindMasterPages()
    {
        ListItem item = null;

        // the xslt template list if applicable
        DirectoryInfo dir = new DirectoryInfo(System.Web.Hosting.HostingEnvironment.MapPath(mWebsite.TemplatesFolder));
        if (dir.Exists)
        {
            DirectoryInfo[] xslTemplates = new DirectoryInfo[0];
            xslTemplates = dir.GetDirectories();

            foreach (DirectoryInfo xslTemplate in xslTemplates)
            {
                if (File.Exists(Path.Combine(xslTemplate.FullName, "template.xsl")))
                {
                    item = new ListItem();
                    item.Text = Path.GetFileNameWithoutExtension(xslTemplate.Name);
                    item.Value = xslTemplate.Name;
                    if (mCurrentPage.MasterPage == item.Value)
                    {
                        item.Selected = true;
                    }
                    ddlMasterPage.Items.Add(item);
                }
            }
        }

        linkPreviewMasterPage.NavigateUrl = Request.ApplicationPath.TrimEnd('/') + "/preview.aspx?guid=" + ((int)CMSObjectType.WebPage).ToString().PadLeft(2, '0') + mCurrentPage.GUID + "&template=" + ddlMasterPage.SelectedValue;

    }

    protected void fckContent_Load(object sender, EventArgs e)
    {

    }
    protected void fvWebPage_Init(object sender, EventArgs e)
    {


    }
    protected void fvWebPage_DataBinding(object sender, EventArgs e)
    {



    }
    protected void ddlMasterPage_SelectedIndexChanged(object sender, EventArgs e)
    {
        linkPreviewMasterPage.NavigateUrl = Request.ApplicationPath.TrimEnd('/') + "/preview.aspx?guid=" + ((int)CMSObjectType.WebPage).ToString().PadLeft(2, '0') + mCurrentPage.GUID + "&template=" + ddlMasterPage.SelectedValue;
    }

    protected void lbConvertToSmartPage_Click(object sender, EventArgs e)
    {
        if (mCurrentPage.PageType == WebPageType.SmartPage)
            mCurrentPage.PageType = WebPageType.Standard;
        else
            mCurrentPage.PageType = WebPageType.SmartPage;

        WebPage.Update(mCurrentPage);

        Response.Redirect("construct/?pid=" + mCurrentPage.ID.ToString());
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        mCurrentPage.State = (CMSObjectState)ddlPageStatus.SelectedIndex;
        mCurrentPage.Title = TitleTextBox.Text;
        mCurrentPage.ItemKey = txtPageKey.Text;
        mCurrentPage.HTMLContent = fckContent.Value;
        mCurrentPage.Website = mWebsite;
        mCurrentPage.PageType = WebPageType.Standard;
        mCurrentPage.PageName = TitleTextBox.Text;
        mCurrentPage.IsBlogPost = ForBlog;

        mCurrentPage.TemplateType = PageTemplateType.XSLT;
        mCurrentPage.MasterPage = ddlMasterPage.SelectedValue;

        ISession session = Configuration.GetCurrentSession();

        try
        {
            session.Save(mCurrentPage);
            session.Flush();

            mWebsite.NeedsPublish = true;
            CMSMasterPage.setPublishLinkVisibility(true);
        }
        catch (Exception ex)
        {
            throw;
        }

        ShowSystemFeedback("The page has been saved");
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (ForBlog)
            Response.Redirect("~/manager/blog");
        else
            Response.Redirect("default.aspx");
    }
}
